﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DMC300Axis_IO.Function;

using csLTDMC;

namespace OCR.SystemThread
{
    public class DIO_Thread
    {
        public static bool DIORun = false;
        public static Thread DIO_StateThread = null;
        public static ushort[] Do = new ushort[32];
        public static ushort[] Di = new ushort[32];

        public static void DIO_State()
        {
            DIORun = true;
            DIO_StateThread = new Thread(DIOThread);
            DIO_StateThread.IsBackground = true;
            DIO_StateThread.Start();
        }
        /// <summary>
        /// DIO线程扫描，一直持续更新状态
        /// </summary>
        /// <param name="obj"></param>
        private static void DIOThread(object obj)
        {
            while (DIORun)
            {
                DI_State_Results(0, 4);
                DIO_Thread.DO_Trigger(0);
                Thread.Sleep(5);
            }
        }
        /// <summary>
        /// DO输出状态更新
        /// </summary>
        /// <param name="sNodeID"></param>
        public static void DO_Trigger(ushort sNodeID)
        {
            for (UInt16 i = 0; i < 16; i++)
            {
                if (Do[i] == 1)
                {
                    LTDMC.dmc_write_outbit(sNodeID, i, 0);     //需要输出时，下达0为输出作动
                }
                else
                {
                    LTDMC.dmc_write_outbit(sNodeID, i, 1);      //下达1为关闭输出
                }
            }            
        }
        /// <summary>
        /// DI输入状态更新
        /// </summary>
        /// <param name="sCount">控制卡编号</param>
        /// <param name="sNodeID">暂时不用</param>
        /// <returns></returns>
        public static short DI_State_Results(ushort sCount, ushort sNodeID)
        {
            short err = 0;
            uint unN = LTDMC.dmc_read_inport(sCount, 0);//读本地输入口的值
            for (int i = 0; i < 16; i++)
            {
                if ((unN & 1) == 0)  //当判断为0时才是有讯号进来
                {
                    Di[i] = 1;
                }
                else Di[i] = 0;
                unN = unN >> 1;//unN变成unN向右移一位的那个数
            }            
            return err;
        }
    }
    
}
